package com.cershy.chatroomserver.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.cershy.chatroomserver.constant.UserType;
import com.cershy.chatroomserver.entity.User;
import com.cershy.chatroomserver.exception.ChatException;
import com.cershy.chatroomserver.mapper.UserMapper;
import com.cershy.chatroomserver.vo.register.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cershy.chatroomserver.entity.UserList;
import com.cershy.chatroomserver.mapper.UserListMapper;

import java.util.Date;

@Service
public class RegisterService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserListMapper userListMapper;

    @Autowired
    private UserMapper userMapper; // 补充注入 UserMapper

    public JSONObject register(RegisterVo registerVo) {
        // 检查用户名或邮箱是否已被占用
        User user = userService.getUserByNameOrEmail(registerVo.getName(), registerVo.getEmail());
        if (user != null) {
            if (registerVo.getName().equals(user.getName()) &&
                    !registerVo.getEmail().equals(user.getEmail())) {
                throw new ChatException("用户名已被使用~");
            }
            if (!registerVo.getName().equals(user.getName()) &&
                    registerVo.getEmail().equals(user.getEmail())) {
                throw new ChatException("邮箱已被使用~");
            }
        }

        // 创建新用户
        user = new User();
        user.setId(IdUtil.simpleUUID());
        user.setName(registerVo.getName());
        user.setEmail(registerVo.getEmail());
        user.setPassword(registerVo.getPassword()); // 实际应加密存储
        user.setType(UserType.User);
        user.setLoginTime(new Date());
        user.setAvatar(""); // 可选默认头像

        // 插入数据库
        userMapper.insert(user);

        // 自动加入默认群聊 group_1
        UserList userList = new UserList();
        userList.setId(IdUtil.simpleUUID()); // 主键ID
        userList.setUserId(user.getId());    // 用户ID
        userList.setGroupId("group_1");      // 默认群ID
        userList.setRole("user");            // 默认角色
        userList.setCreateTime(new Date());
        userList.setUpdateTime(new Date());

        userListMapper.insert(userList);

        // 构造返回结果
        JSONObject userinfo = new JSONObject();
        userinfo.put("userId", user.getId());
        userinfo.put("userName", user.getName());
        userinfo.put("email", user.getEmail());
        userinfo.put("type", user.getType());

        return userinfo;
    }
}
